package com.sunny.hp.common.util;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.support.RequestContextUtils;



public class HttpRequest
{
	protected HttpServletRequest m_req;
	protected String strNullParam ;
	protected String m_method ;
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * HttpRequest
	 * @param request
	 * @return
	 * @throws
	 */
	public HttpRequest(HttpServletRequest request)
	{
		m_req = request;
		strNullParam = null;
		m_method = request.getMethod();
	}


	/**
	 * @throws UnsupportedEncodingException
	 * _get_parameter
	 * @param varName
	 * @return String
	 * @throws
	 */
	protected String _get_parameter(String varName) throws UnsupportedEncodingException
	{
		CharacterConversion csChar	= new CharacterConversion();
		if("GET".equals(m_method)){
			//return csChar.unesacpeE2U(m_req.getParameter(varName.trim()));
			logger.debug("request Parameter : " + varName.trim() + " : " + m_req.getParameter(varName.trim()));
			return m_req.getParameter(varName.trim());
		}else{
			/*
            if(m_req.getRequestURL().indexOf("dev") > 0)				// �?컬�??�?
                return toKorean(m_req.getParameter(varName.trim()));
            else
                return m_req.getParameter(varName.trim());				// ??��??�?
			 */
			//return csChar.unesacpeE2U(m_req.getParameter(varName.trim()));
			logger.debug("request Parameter : " + varName.trim() + " : " + m_req.getParameter(varName.trim()));
			return m_req.getParameter(varName.trim());

		}


		// return m_req.getParameter(varName.trim());
		// return toKorean(m_req.getParameter(varName.trim()));

	}


	/**
	 * getFormatNumber
	 * @param n, str
	 * @return String
	 * @throws
	 */
	public String getFormatNumber(int n, String str)
	{
		StringBuffer sb = new StringBuffer();
		String nStr = n + "";
		try
		{
			int nLength = nStr.length();
			int nComma = 3-nLength%3;
			if (nComma == 3) nComma = 0;
			for(int i=0; i<nLength; i++)
			{
				if (nComma==3)
				{
					sb.append(str);
					nComma = 0;
				}
				sb.append( nStr.charAt(i));
				nComma++;
			}

		}
		catch(Exception e)
		{
			//throw e;
		}
		return sb.toString();
	}


	/**
	 * getFormatNumber
	 * @param d, str
	 * @return String
	 * @throws
	 */
	public String getFormatNumber(double d, String str)
	{
		StringBuffer sb = new StringBuffer();
		String dStr = d + "";
		String nStr = dStr.substring(0, dStr.indexOf("."));
		String eStr = dStr.substring(dStr.indexOf("."), dStr.length());
		try
		{
			int nLength = nStr.length();
			int nComma = 3-nLength%3;
			if (nComma == 3) nComma = 0;
			for(int i=0; i<nLength; i++)
			{
				if (nComma==3)
				{
					sb.append(str);
					nComma = 0;
				}
				sb.append( nStr.charAt(i));
				nComma++;
			}
			sb.append(eStr);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return sb.toString();
	}


	/**
	 * NVL
	 * @param str, bDefault
	 * @return boolean
	 * @throws
	 */
	public boolean NVL(String str, boolean bDefault)
	{
		boolean r = bDefault;
		try
		{
			if (str != null)
				r = Boolean.getBoolean(str);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return r;
	}


	/**
	 * NVL
	 * @param str, nDefault
	 * @return int
	 * @throws
	 */
	public int NVL(String str, int nDefault)
	{
		int r = nDefault;
		try
		{
			if (str != null)
				r = Integer.parseInt(str);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return r;
	}


	/**
	 * NVL
	 * @param str, dDefault
	 * @return double
	 * @throws
	 */
	public double NVL(String str, double dDefault)
	{
		double r = dDefault;
		try
		{
			if (str != null)
				r = Double.parseDouble(str);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return r;
	}


	/**
	 * NVL
	 * @param str, strDefault
	 * @return String
	 * @throws
	 */
	public String NVL(String str, String strDefault)
	{
		String r = strDefault;
		try
		{
			if (str != null)
				r = str;
		}
		catch(Exception e)
		{
			//throw e;
		}
		return r;
	}


	/**
	 * getNullParamName
	 * @param
	 * @return String
	 * @throws
	 */
	public String getNullParamName()
	{
		return strNullParam;
	}


	/**
	 * resetNullParamName
	 * @param
	 * @return
	 * @throws
	 */
	public void resetNullParamName()
	{
		strNullParam = null;
	}


	/**
	 * getBoolean
	 * @param varName
	 * @return boolean
	 * @throws
	 */
	public boolean getBoolean(String varName)
	{
		String str = null;
		boolean x = false;
		try
		{
			str = _get_parameter(varName);
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName.trim();
			}
			else
				x = Boolean.getBoolean(str);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return x;
	}


	/**
	 * getInt
	 * @param varName
	 * @return int
	 * @throws
	 */
	public int getInt(String varName)
	{
		String str = null;
		int x = 0;
		try
		{
			str = _get_parameter(varName);
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName.trim();
			}
			else
				x = Integer.parseInt(str);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return x;
	}


	/**
	 * getString
	 * @param varName
	 * @return String
	 * @throws
	 */
	public String getString(String varName)
	{
		String str = null;
		try
		{
			str = _get_parameter(varName);
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName;
			}
		}
		catch(Exception e)
		{
			//throw e;
		}

		if(str==null)
			str = "";

		return str;
	}

	/**
	 * getStringUTF
	 * @param varName
	 * @return String
	 * @throws
	 */
	public String getStringUTF(String varName) throws Exception
	{
		m_req.setCharacterEncoding("UTF-8");

		String str = null;
		try
		{
			str = m_req.getParameter(varName.trim());
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName;
			}
		}
		catch(Exception e)
		{
			//throw e;
		}

		if(str==null)
			str = "";

		return str;
	}

	/**
	 * getDouble
	 * @param varName
	 * @return double
	 * @throws
	 */
	public double getDouble(String varName)
	{
		String str = null;
		double x = 0.0;
		try
		{
			str = _get_parameter(varName);
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName.trim();
			}
			else
				x = Double.parseDouble(str);
		}
		catch(Exception e)
		{
			//throw e;
		}
		return x;
	}


	/**
	 * getInt :  m_req.getString, getInt 2�? ?????��?��?? <- default value
	 * @param varName, nDefault
	 * @return int
	 * @throws
	 */
	public int getInt(String varName, int nDefault)
	{
		String str = null;
		int x = nDefault;
		try
		{
			str = _get_parameter(varName);
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName.trim();
			}
			else
			{
				if (str.equals(""))
				{
					if (strNullParam==null)
						strNullParam = varName.trim();
				}
				else
					x = Integer.parseInt(str);
			}
		}
		catch(Exception e)
		{
			//throw e;
		}
		return x;
	}


	/**
	 * getString
	 * @param varName, strDefault
	 * @return String
	 * @throws
	 */
	public String getString(String varName, String strDefault)
	{
		String str = null;

		try
		{
			str = _get_parameter(varName);

			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName;
			}
			else
			{
				if (str.equals(""))
				{
					if (strNullParam==null)
						strNullParam = varName.trim();
					str = strDefault;
				}
			}

		}
		catch(Exception e)
		{
			//throw e;
		}

		if(str==null)
			str = strDefault;

		return str;
	}


	/**
	 * getDouble
	 * @param varName, nDefault
	 * @return double
	 * @throws
	 */
	public double getDouble(String varName, double nDefault)
	{
		String str = null;
		double x = nDefault;
		try
		{
			str = _get_parameter(varName);
			if (str == null)
			{
				if (strNullParam==null)
					strNullParam = varName.trim();
			}
			else
			{
				if (str.equals(""))
				{
					if (strNullParam==null)
						strNullParam = varName.trim();
				}
				else
					x = Double.parseDouble(str);
			}
		}
		catch(Exception e)
		{
			//throw e;
		}
		return x;
	}


	/**
	 * getDouble
	 * @param varName, nDefault
	 * @return String
	 * @throws
	 */
	static public String statLPAD(String strOrg, int length, String fillString)
	{
		int nLength = strOrg.length();

		if (fillString.length() != 1) return strOrg;
		if (length <= nLength) return strOrg;

		String strRepeat = "";
		for(int i=0; i< length-nLength; i++)
		{
			strRepeat += fillString;
		}
		return (strRepeat + strOrg);
	}


	/**
	 * LPAD
	 * @param strOrg, length, fillString
	 * @return String
	 * @throws
	 */
	public String LPAD(String strOrg, int length, String fillString)
	{
		//return itskorea.request.HttpRequest.statLPAD(strOrg, length, fillString);
		return HttpRequest.statLPAD(strOrg, length, fillString);
	}


	/**
	 * toKorean
	 * @param str
	 * @return String
	 * @throws
	 */
	public String toKorean(String str)
	{
		if (str == null) return str;
		String result = null;
		try
		{
			result = new String(str.getBytes("8859_1"), "EUC-KR");
		}
		catch (Exception e)
		{
			//
		}
		return result;
	}


	/**
	 * toEnglish
	 * @param str
	 * @return String
	 * @throws
	 */
	public String toEnglish(String str)
	{
		if (str == null) return str;
		String result = null;
		try
		{
			result = new String(str.getBytes("EUC-KR"), "8859_1");
		}
		catch (Exception e)
		{
			//
		}
		return result;
	}

	/**
	 * getParameterValuesToKorean
	 * @param str
	 * @return String[]
	 * @throws
	 */
	public String[] getParameterValuesToKorean(String varName)
	{
		String strTemp[] = null;

		strTemp = m_req.getParameterValues(varName.trim());
		if(strTemp != null){
			if("POST".equals(m_method)){
				for(int i=0; i<strTemp.length; i++){

					if(m_req.getRequestURL().indexOf("dev") > 0)				// �?컬�??�?(??�캣)
						strTemp[i] = toKorean(strTemp[i]);
					else
						strTemp[i] = strTemp[i];				// ??��??�?(?????��??)
				}
			}
		}
		return strTemp;


	}

	public static LinkedHashMap<String, Object> getMapNoEscape(HttpServletRequest request) throws Exception {
		LinkedHashMap<String, Object> param = new LinkedHashMap<String, Object>();


		Enumeration enums = request.getParameterNames();
		while (enums.hasMoreElements()) {
			String name = (String) enums.nextElement();
			String[] values = request.getParameterValues(name);

			if (values != null) {
				if (values.length >= 1){
					param.put(name, values[0]);
					param.put(name, values);
				}else if (values.length < 1){
					param.put(name, "");
					param.put(name + "_arr", null);
				}
			} else
				param.put(name, "");
		}
		return param;
	}

	public LinkedHashMap<String, Object> paramBind(){
		LinkedHashMap<String, Object> param = new LinkedHashMap<String, Object>();
		if(NVL(m_req.getParameter("bm"),"N").equals("Y")){
			//FlashMap에 저장되어 전달된 값을 가져온다. 
			Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(m_req); 
			if(flashMap !=null) { 
				Set<String> keys = flashMap.keySet();
				for(String key : keys){
					param.put(key, flashMap.get(key));
				}
			}
		}else{
			Enumeration enums = m_req.getParameterNames();
			while (enums.hasMoreElements()) {

				String name = (String) enums.nextElement();
				//System.out.println("name : " + name);
				String[] values = m_req.getParameterValues(name);

				if (values != null) {
					if (values.length >= 1){
						param.put(name, getSTRFilter(values[0]));
						param.put(name + "_arr", getSTRFilterArr(values));
					}else if (values.length < 1){
						param.put(name, "");
						param.put(name + "_arr", null);
					}
				} else
					param.put(name, "");
			}
		}
		return param;
	}

	public static String[] getSTRFilterArr(String str[]){
		String str_imsi   = "";
		//        String[] filter_word = {"\'","\"","\\@","\\#","\\$","\\%","\\&","\\*","\\(","\\)","\\+","\\=","\\|","\\\\","\\}","\\]","\\{","\\[","\\\"","\\'","\\:","\\;","\\<","\\,","\\>","\\.","\\?","\\/"};
		String[] filter_word = {"\'","\"","\\/\\*","\\'","\\;","\\*\\/"};
		//        String[] filter_word = {"\'","\"","\\/\\*","\\'","\\*\\/","\\#"};
		for (int j=0;j < str.length;j++) {
			for(int i=0;i<filter_word.length;i++){
				str_imsi = str[j].replaceAll(filter_word[i],"");
				str[j] = str_imsi;
			}
			//            str[j].replaceAll("\\<", "&lt;");
			//            str[j].replaceAll("\\>", "&gt;");
		}

		return str;
	}
	public static String getSTRFilter(String str){
		String str_imsi   = "";
		//      String[] filter_word = {"\'","\"","\\@","\\#","\\$","\\%","\\&","\\*","\\(","\\)","\\+","\\=","\\|","\\\\","\\}","\\]","\\{","\\[","\\\"","\\'","\\:","\\;","\\<","\\,","\\>","\\.","\\?","\\/"};
		String[] filter_word = {"\'","\"","\\/\\*","\\'","\\;","\\*\\/"};
		//         String[] filter_word = {"\'","\"","\\/\\*","\\'","\\*\\/","\\#"};
		for(int i=0;i<filter_word.length;i++){
			str_imsi = str.replaceAll(filter_word[i],"");
			str = str_imsi;
		}
		//         str.replaceAll("\\<", "&lt;");
		//         str.replaceAll("\\>", "&gt;");
		return str;
	}

}
